<template>
	<view>
		<custom-header title="物料管理" :isConfirm="isComplete" @confirm="confirm" :showDelete="showDelete" @delete="onDel" />
		<u-sticky :customNavHeight="height">
			<u-tabs class="tabs" :list="tabsList" @click="onTabClick" :scrollable="false"
				style="padding: 0 24rpx; background: #fff; z-index: 22; position: sticky; top: 0px"
				:activeStyle="{ color: '#171717', fontSize: '16px', fontWeight: 500 }"
				:inactiveStyle="{ color: '#C6C6C6', fontSize: '16px', fontWeight: 500 }" lineColor="#1E6FFF"></u-tabs>
		</u-sticky>
		<!-- #ifdef APP-PLUS -->
		<view style="height: 40px;"></view>
		<!-- #endif -->
		<view class="task_lists" :style="{ marginTop: '50px' }">
			<collapse name="基础信息" id="outside1" :maxHeight="maxHeight1" :borderRadius="0" :hasIcon="true">
				<view class="listdefault" :id="uId1">
					<view class="action" v-for="(item, index) in basicInfo" :key="index"
						:style="{ width: item.labelWidth + '%' }">
						<view class="list1">{{ item.label }}</view>
						<view class="list2">
							<template v-if="detailData[item.key]">
								<template v-if="item.key === 'provisionBroad'">
									<custom-dropdown disabled class="w-100" keyName="categoryName" border="none"
										:api="api.queryProvisionBroadList" v-model="detailData[item.key]"
										dataKey="result" />
								</template>
								<template v-else-if="item.key === 'provisionSmall'">
									<custom-select-material-small class="w-100" :muitFlag="true"
										:parentId="detailData.provisionBroad" v-model="detailData[item.key]"
										placeholder="请选择物料小类" border="none" disabled></custom-select-material-small>
								</template>
								<template v-else>
									{{ detailData[item.key] }}
								</template>
							</template>
							<text v-else-if="!detailData[item.key] && item.required && isClick" class="red">{{ item.tipType === 1 ? '请输入' : '请选择' }}{{ item.label }}</text>
						</view>
					</view>
				</view>
				<view slot="handler" class="btn-edit" v-if="showEdit" @click="goEdit(APPTYPE.CONTACTUNIT)">编辑</view>
			</collapse>
			<default-list name="附件信息" :borderRadius="0" :hasIcon="true" id="outside2">
				<view v-for="(item, index) in attachment" :key="index">
					<view class="file-type">{{ item.label }}</view>
					<file-list :fileList="detailData[item.key]" :required="false" :empty-text="'请选择' + item.label"
						empty-text-color="red"></file-list>
					<!-- <view class="file-type-line" v-if="index !== companyDataInfo.length - 1"></view> -->
				</view>
				<view slot="handler" class="btn-edit" v-if="showEdit" @click="goEdit(APPTYPE.COMPANYDATA)">编辑</view>
			</default-list>
		</view>
		<view style="height: 100px;" v-if="showSave || showDelete"></view>
		<view class="space-x-1 px-1 btn_position" v-if="showSave">
			<u-button type="primary" :plain="true" text="保存" @click="onDraft"
				:disabled="$hasPerm('erpMaterial:submit') || isSubmit"></u-button>
			<u-button type="primary" text="提交" @click="onSubmit"
				:disabled="$hasPerm('erpMaterial:submit') || isSubmit"></u-button>
		</view>
		<view class="space-x-1 px-1 btn_position" v-if="showDelete">
			<u-button type="primary" :plain="true" text="编辑" @click="onEdit"
				:disabled="$hasPerm('erpMaterial:delete') || isSubmit"></u-button>
			<u-button type="primary" text="提交" @click="onSubmit"
				:disabled="$hasPerm('erpMaterial:edit') || isSubmit"></u-button>
		</view>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>
<script>
import APPTYPE from '@/config/appType.js'
import {
	mapState
} from 'vuex'
import moment from 'moment'
import fileList from '@/pages/purchase/components/fileList.vue'
import collapse from '@/pages/purchase/components/collapse.vue'
import defaultList from '@/pages/purchase/components/defaultList.vue'
import {
	queryById,
	submit,
	edit,
	add,
	deleteData
} from '@/api/purchase/ErpMaterial.js'
import {
	queryProvisionBroadList,
	queryProvisionSmallList
} from '@/api/purchase/ErpPurchaseCannibalizeForm'
export default {
	data() {
		return {
			api: {
				queryProvisionSmallList,
				queryProvisionBroadList,
			},
			isClick: false, // 是否点击
			APPTYPE: APPTYPE,
			tabsList: [{
				name: '基础信息',
				id: 'outside1'
			}, {
				name: '附件信息',
				id: 'outside2'
			}],
			childTable: [],
			detailData: {
				materialBill: '',
				provisionBroad: '',
				provisionSmall: '',
				materialName: '',
				specification: '',
				brand: '',
				manufacturer: '',
				production: '',
				referencePrice: '',
				unit: '',
				ohterOne: '',
				ohterTwo: '',
				remark: '',
			}, // 详情数据
			basicInfo: [
				{
					label: '物料名称',
					key: 'materialName',
					labelWidth: 100,
					tipType: 1,
					required: true
				},
				{
				label: '物料编码',
				key: 'materialBill',
				tipType: 1,
				required: false 
			},
			{
				label: '物料大类',
				key: 'provisionBroad',
				tipType: 2,
				required: true
			},
			{
				label: '物料小类',
				key: 'provisionSmall',
				tipType: 2,
				required: true
			},
			{
				label: '规格型号',
				key: 'specification',
				tipType: 1,
				required: true
			},
			{
				label: '品牌',
				key: 'brand',
				tipType: 1,
				required: false
			},
			{
				label: '制造商',
				key: 'manufacturer',
				tipType: 1,
				required: false
			},
			{
				label: '产地',
				key: 'production',
				tipType: 1,
				required: false
			},
			{
				label: '参考价格（元）',
				key: 'referencePrice',
				tipType: 1,
				required: true
			},
			{
				label: '单位',
				key: 'unit_dictText',
				tipType: 2,
				required: false
			},
			{
				label: '其他属性1',
				key: 'ohterOne',
				labelWidth: 100,
				tipType: 1,
				required: false
			},
			{
				label: '其他属性2',
				key: 'ohterTwo',
				labelWidth: 100,
				tipType: 1,
				required: false
			},
			{
				label: '备注',
				key: 'remark',
				labelWidth: 100,
				tipType: 1,
				required: false
			}
			],
			attachment: [{
				label: '附件',
				key: 'attachment',
				required: false
			}],
			scrollTop: 0, // 滚动顶部距离
			maxHeight1: 0,
			// maxHeight2: 0,
			uId1: uni.$u.guid(),
			// uId2: uni.$u.guid(),
			formType: null,
			height: 37,
			smallList: [],
			isSubmit: false,
			inRequire: [
				'provisionBroad',
				'provisionSmall',
				'materialName',
				'specification',
				'referencePrice',
			],
			isComplete: false,
			showSave: false,
			showDelete: false,
			loading: false,
			id: null
		}
	},
	components: {
		fileList,
		collapse,
		defaultList,
	},
	computed: {
		...mapState(['userInfo']),
		showEdit() {
			return this.formType === this.APPTYPE.ADD
		},
	},
	onPageScroll(e) {
		this.scrollTop = e.scrollTop
	},
	created() {
		const type = this.formType;
		if (type) {
			// if (type === this.APPTYPE.ADD) {
			// 	this.initForm()
			// }
			if (type === this.APPTYPE.EDIT) {
				this.showDelete = true
			}
		}
		uni.getSystemInfo({
			success(e) {
				uni.setStorageSync('getSystemInfo', e);
			}
		})
		let safeArea = uni.getStorageSync('getSystemInfo').safeArea.top
		this.height = safeArea + 37
	},
	onReady() {
		this.setCollapseHeight()
	},
	onLoad(options) {
		options && options.id && this.loadData(options.id);
		this.formType = options.formType || null;
		var that = this
		uni.$on(that.APPTYPE.CONTACTUNIT, function (data) {
			that.isClick = true
			that.detailData = Object.assign({}, that.detailData, data);
			that.setCollapseHeight()
			that.isComplete = that.formFieldComplete()
		});
		// uni.$on(that.APPTYPE.CONTACTS, function (data) {
		// 	that.childTable = data
		// 	that.setCollapseHeight()
		// 	that.isComplete = that.formFieldComplete()
		// });
		uni.$on(that.APPTYPE.COMPANYDATA, function (data) {
			that.isClick = true
			that.detailData = Object.assign({}, that.detailData, data);
			that.isComplete = that.formFieldComplete()
		});
	},
	onUnload() {
		uni.$off(this.APPTYPE.CONTACTUNIT);
		// uni.$off(this.APPTYPE.CONTACTS);
		uni.$off(this.APPTYPE.COMPANYDATA);
	},
	methods: {
		updatePrevPageList() {
			let pages = getCurrentPages();
			let prevPage = pages[pages.length - 2] //上一页页面实例
			if ('undefined' !== typeof prevPage) {
				// #ifdef APP-PLUS
				prevPage = prevPage.$vm;
				// #endif
				prevPage.getList();
				prevPage.getTotla();
			}
		},
		async onDraft() {
			this.isClick = true
			this.isSubmit = true
			try {
				this.loading = true
				var url = ''
				if (this.id) {
					url = edit
				} else {
					url = add
				}
				const response = await url({
					...this.detailData,
					// detailList: this.childTable,
				})
				if (response.success) {
					var that = this
					that.updatePrevPageList()
					this.$refs.uToast.show({
						message: response.message,
						type: 'default',
						complete() {
							uni.navigateBack()
						}
					})
				} else {
					this.$refs.uToast.show({
						message: response.message,
						type: 'default'
					})
				}
			} finally {
				// this.loading = false
			}
		},
		async submit() {
			this.isClick = true
			const that = this
			// if (that.childListEmpty()) {
			// 	that.$u.toast('请添加联系人信息！');
			// 	return;
			// }
			if (!that.formFieldComplete()) {
				that.$u.toast('请填写必填项信息！');
				return;
			}
			that.isSubmit = true
			try {
				this.loading = true
				var url = ''
				if (this.id) {
					url = edit
				} else {
					url = add
				}
				const response = await url({
					...this.detailData,
					// detailList: this.childTable,
				})
				if (response.success) {
					if (!this.id) {
						this.id = response.result.id
					}
					this.onProcess()
				}
			} finally {
				// this.loading = false
			}
		},
		
		async onProcess () {
			var that = this
			try {
				var url = submit
				const response = await url({
					id: that.id
				})
				if (response.success) {
					that.updatePrevPageList()
					that.$refs.uToast.show({
						message: response.message,
						type: 'default',
						complete() {
							uni.navigateBack()
						}
					})
				}
			} finally {
				// this.loading = false
			}
		},
		onSubmit() {
			const that = this
			uni.showModal({
				content: '确定提交吗',
				success: function (res) {
					if (res.confirm) {
						that.submit();
					}
				}
			});
		},
		onEdit() {
			this.formType = APPTYPE.ADD
			this.showDelete = false
		},
		onDel() {
			let that = this;
			uni.showModal({
				content: '确定删除吗',
				success: function (res) {
					if (res.confirm) {
						deleteData({ id: that.id }).then((res) => {
							if (res.success) {
								that.updatePrevPageList()
								that.$u.toast(res.message);
								if (getCurrentPages().length > 1) {
									uni.navigateBack()
								} else {
									uni.reLaunch({
										url: '/pages/home/home'
									})
								}
							} else {
								that.$u.toast(res.message);
							}
						});
					}
				}
			});
		},
		confirm(data) {
			this.isComplete = false;
			this.showSave = true;
			this.formType = APPTYPE.EDIT
		},
		isNull(value) {
			return value === '' || value === null || value === undefined
		},
		// childListEmpty() {
		// 	return this.childTable.length === 0
		// },
		formFieldComplete() {
			let isComplete = false;
			const self = this;
			for (let key in self.detailData) {
				if (self.inRequire.includes(key)) {
					if (self.isNull(self.detailData[key])) {
						isComplete = false;
						break;
					} else {
						isComplete = true;
					}
				}
			}
			// const empty = self.childListEmpty()
			// if (empty) {
			// 	isComplete = !empty
			// }
			return isComplete;
			// self.isComplete = isComplete;
		},
		goEdit(tpe) {
			let _url = '';
			switch (tpe) {
				case this.APPTYPE.CONTACTUNIT:
					_url = '/pages/purchase/components/ErpMaterialBaseForm?formData=' + encodeURIComponent(JSON.stringify(
						this.detailData))
					break;
				// case this.APPTYPE.CONTACTS:
				// 	_url = '/pages/purchase/components/ContactsForm?formData=' + encodeURIComponent(JSON.stringify(
				// 		this.childTable))
				// 	break;
				default:
					_url = '/pages/purchase/components/CompanyDataForm?formData=' + encodeURIComponent(JSON.stringify(
						this.detailData)) + '&companyData=' + encodeURIComponent(JSON.stringify(
							this.attachment)) + '&uploadImage=1'
					break;
			}
			uni.navigateTo({
				url: _url
			})
		},
		// 初始化新增需要的数据
		// initForm() {
		// 	this.detailData.proposer = this.userInfo.empId //当前登录人
		// 	this.detailData.proposerDeptId = this.userInfo.deptId //当前登录人部门
		// 	this.detailData.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
		// },
		findProvisionSmallList(value) {
			const parentId = value
			queryProvisionSmallList({
				parentId
			}).then((res) => {
				if (res.success) {
					const data = res.result.map((item) => {
						return {
							id: item.id,
							categoryName: item.categoryName
						}
					})
					this.smallList = [data]
				} else {
					this.$u.toast(res.message)
				}
			})
		},
		// getChildTable(id) {
		// 	childList({
		// 		pageNo: 1,
		// 		pageSize: 100,
		// 		mainId: id,
		// 		column: 'createTime',
		// 		order: 'desc',
		// 		field: 'id',
		// 	}).then((response) => {
		// 		this.childTable = response.result || []
		// 	})
		// },
		// 查询预立项申请详情
		loadData(id) {
			this.id = id;
			queryById({
				id
			}).then((res) => {
				if (res.success) {
					this.detailData = res.result
					this.$nextTick(function () {
						this.setCollapseHeight(this.detailData.rejectExcuse ? true : false)
					})
					// this.getChildTable(this.detailData.id)
				} else {
					this.$refs.uToast.show({
						message: res.message,
						type: 'error',
					})
				}
			})
		},
		setCollapseHeight(reject) {
			this.timer = setTimeout(() => {
				clearTimeout(this.timer)
				this.timer = null
				this.$nextTick(function () {
					uni
						.createSelectorQuery()
						.select('#' + this.uId1)
						.boundingClientRect((data) => {
							this.maxHeight1 = data.height
						})
						.exec()
				})
				// this.$nextTick(function () {
				// 	uni
				// 		.createSelectorQuery()
				// 		.select('#' + this.uId2)
				// 		.boundingClientRect((data) => {
				// 			this.maxHeight2 = data.height
				// 		})
				// 		.exec()
				// })
				// this.$nextTick(function () {
				// 	uni
				// 		.createSelectorQuery()
				// 		.select('#' + this.uId3)
				// 		.boundingClientRect((data) => {
				// 			this.maxHeight3 = data.height
				// 		})
				// 		.exec()
				// })
			}, 300)
		},
		// 点击tabs
		onTabClick(item) {
			uni
				.createSelectorQuery()
				.in(this)
				.select(`#${item.id}`)
				.boundingClientRect((data) => {
					uni.pageScrollTo({
						scrollTop: data.top + this.scrollTop - 54,
						duration: 150,
					})
				})
				.exec()
		},
	},
}
</script>
<style lang="scss" scoped>
@import '@/pages/synergy/common/actionNew.scss';
@import url('@/assets/inputStyle.scss');

// .task_lists {
// 	padding: 20rpx 20rpx 0;
// }

.file-type {
	margin-top: 20rpx;
	font-size: 14px;
	// font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: #B2B2B2;
}

.file-type-line {
	margin: 20rpx 0 0;
	width: 100%;
	background: rgba(0, 0, 0, 0.1);
	height: 2rpx;
}

.red {
	color: red;
}

.btn-edit {
	padding: 24rpx 0;
	// font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: #1E6FFF;
	text-align: center;
	border-top: 1rpx solid rgba(0, 0, 0, 0.1);
}

.reject-reason {
	padding: 8px 16px;
}
</style>